﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using Telerik.Windows.Controls;

namespace LeoK.Common.Converter
{
    public class MinutesToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            int minutes = (int)value;
            TimeSpan timeSpan = TimeSpan.FromMinutes(minutes);
            string result = "";
            if (timeSpan.Days > 0)
            {
                result += timeSpan.Days + "天";
            }
            if (timeSpan.Hours > 0)
            {
                result += timeSpan.Hours + "小时";
            }
            if (timeSpan.Minutes > 0)
            {
                result += timeSpan.Minutes + "分";
            }

            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string str = value.ToString();
            int result = 0;
            if (!Int32.TryParse(str, out result))
            {
                try
                {
                    if (str.Contains("天"))
                    {
                        string dayStr = str.Substring(0, str.IndexOf('天'));
                        str = str.Substring(str.IndexOf('天') + 1);
                        int day = Int32.Parse(dayStr);
                        result = 24 * 60 * day;
                    }
                    if (str.Contains("小时"))
                    {
                        string hourStr = str.Substring(0, str.IndexOf('小'));
                        str = str.Substring(str.IndexOf('小') + 2);
                        int hour = Int32.Parse(hourStr);
                        result += 60 * hour;
                    }
                    if (str.Contains("分"))
                    {
                        result += Int32.Parse(str.TrimEnd('分'));
                    }
                }
                catch (Exception)
                {
                    RadWindow.Alert("输入的字符串不正确");
                }
            }

            return result;
        }
    }
}
